package lj.a.tool;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import ntd.util.fun.ComFun;

import java.io.File;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedDeque;

/**
 * @author: liuwenju
 * @date: 2023/6/25 13:27
 * @version: 1.0
 */
public class LJToolFile {

    public static final int MAX_NUM = 99999;

    public static List<File> loopFiles(String path) {
        return loopFiles(path, null);
    }

    public static void loopStreamFiles(String path, ComFun.FunInNoException<File> comFun) {
        if (FileUtil.isFile(path)) {
            comFun.accept(FileUtil.file(path));
            return;
        }

        File[] fileNames = FileUtil.ls(path);

        if (ArrayUtil.isEmpty(fileNames)) {
            return;
        }

        for (int i = 0; i < fileNames.length; i++) {
            File file = fileNames[i];
            if (FileUtil.isDirectory(file)) {
                loopStreamFiles(file.getPath(), comFun);
            } else {
                comFun.accept(file);
            }
        }
    }

    public static List<File> loopFiles(String path, ConcurrentLinkedDeque<File> res) {
        if (ObjectUtil.isNull(res)) {
            res = new ConcurrentLinkedDeque<>();
        }
        if (StrUtil.isBlank(path) || res.size() > MAX_NUM) {
            return ListUtil.empty();
        }
        if (FileUtil.isFile(path)) {
            return ListUtil.of(FileUtil.file(path));
        }
        StaticLog.info("LJ - 开始遍历[{}]...", path);

        File[] fileNames = FileUtil.ls(path);

        if (ArrayUtil.isEmpty(fileNames)) {
            return ListUtil.toList(res);
        }

        for (int i = 0; i < fileNames.length; i++) {
            File file = fileNames[i];
            if (FileUtil.isDirectory(file)) {
                loopFiles(file.getPath(), res);
            } else {
                if (res.size() > MAX_NUM) {
                    return ListUtil.toList(res);
                }
                res.add(file);
            }
        }

        return ListUtil.toList(res);
    }

    public static void main(String[] args) {
//        List<File> files = loopFiles("C:\\Users\\17391", null);
//        StaticLog.info("ssss" + files.size() + JSONUtil.toJsonStr(files));

        loopStreamFiles("C:\\Users\\17391", file -> StaticLog.info("读取到文件[{}]", file.getPath()));
    }
}
